<template>
  <NavBar></NavBar>
  <div class="image-box">
    <h1 class="title">压缩JPG</h1>
    <h2 class="tool__header__subtitle">压缩 JPG时保持最佳文件质量和压缩程度。在线缩小JPG图片文件的尺寸。</h2>
    <div class="image-compressor">
      <el-upload
        class="upload-demo"
        action="#"
        :before-upload="handleBeforeUpload"
        :on-success="handleSuccess"
        :file-list="fileList"
        :auto-upload="false"
        drag
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">或将图片拖至此处，单次最多可选1张</div>
      </el-upload>

      <div v-if="compressedImage !== null" class="image-container">
        <a :href="compressedImage" download="compressed_image.jpg">
          <img :src="compressedImage" alt="Compressed Image">
        </a>
        <el-button @click="downloadImage" class="download-button" type="primary">下载图片</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import NavBar from '@/components/NavBar/NavBar.vue';
import { compressImage } from '@/util/imageUtils.js';

const fileList = ref([]);
const compressedImage = ref(null);

const handleBeforeUpload = (file) => {
  fileList.value = [file];
  return false; // Prevent automatic upload
};

const handleSuccess = async (response, file) => {
  try {
    const compressed = await compressImage(file.raw);
    compressedImage.value = compressed;
    console.log(111111111111);
  } catch (error) {
    console.error('Error compressing image:', error);
  }
};

const downloadImage = () => {
  if (!compressedImage.value) return;
  const link = document.createElement('a');
  link.href = compressedImage.value;
  link.download = 'compressed_image.jpg';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style scoped>
.title {
  font-weight: 600;
  font-size: 42px;
  line-height: 52px;
  color: #33333b;
  text-align: center;
}
.tool__header__subtitle {
  max-width: 420px;
  margin: 8px auto 0;
  line-height: 32px;
  font-size: 22px;
  font-weight: 400;
  color: #47474f;
}
.image-box {
  height: 100vh!important;
  margin-top: 80px;
  background-color: #F5F5FA;
}
.image-container {
  margin-top: 20px;
  position: relative;
}
.image-container img {
  max-width: 100%;
  height: auto;
}
.download-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
  padding: 8px 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.download-button:hover {
  background-color: #0056b3;
}
.image-compressor {
  max-width: 600px;
  margin: 80px auto;
  padding: 20px;
  background-color: #F5F5FA;
}
</style>
